---@class RedRob.StateController
---@field New fun():RedRob.StateController
local StateController = RedRob.CreateClass("StateController")
---@param actor RedRob.Player
function StateController:OnCreate(actor)
    self.actor = actor
    ---@type RedRob.StateBase
    self.curActionState = nil
end
function StateController:OnDestroy()
    self.actor = nil
    self.curActionState = nil
end
function StateController:EnterState(stateId,data)
    if self.actor == nil then return end
    local state = self.actor:GetActionState()
    if state and state.stateId == stateId then
        if data ~= state.data then
            RedRob.PoolMgr.ReturnStateDataToPool(state.data)
        end
        state:BaseEnter(self.actor,data)
        return
    end
    self:ExitState(self.actor)
    local newState = self:CreateState(stateId)
    if newState then
        newState:BaseEnter(self.actor,data)
        self.curActionState = newState
    end
end
function StateController:IsStateFinished()
    if not self.curActionState then return false end
    return self.curActionState:IsFinished()
end

function StateController:ExitState()
    if self.actor == nil then return end
    local state = self.actor:GetActionState()
    if state ~= nil then
        RedRob.PoolMgr.ReturnStateDataToPool(state.data)
        state:BaseExit()
        RedRob.PoolMgr.ReturnStateToPool(state)
    end
end
---@return RedRob.StateBase
function StateController:CreateState(stateId)
    return RedRob.PoolMgr.GetStateFromPool(stateId)
end

function StateController:Update(dt)
    if not self.curActionState then return end
    if self.curActionState then
        self.curActionState:BaseUpdate(dt)
    end
    local nextId = self.curActionState:GetNextStateId()
    if self.curActionState:IsFinished() and nextId > 0 then
        self:EnterState(nextId)
    end
end

